package com.vivachek.protocol.utils

import com.vivachek.protocol.END
import com.vivachek.protocol.START
import com.vivachek.protocol.enums.CommandEnums

/**
 * @Author: YCB
 * @Time: 2022/10/9 16:29:56
 * @Email: congbin.yuan@vivachek.com
 * @Description: 指令工具类
 */
object CommandUtil {

    fun generateCmd(command: Int, expand: Int, len1: Int,len2:Int,data:List<Int>): ByteArray {
        return if (len1 == 0 && len2==0) {
            generate(command, expand, len1,len2)
        }else if ((len1+len2)==data.size){
            generate(command,expand,len1,len2,data.map { it.toByte() })
        } else {
            val convertData = when(CommandEnums.convert(command, expand, len1,len2)){
                CommandEnums.SET_TIME -> CommandHelper.setTime()
            }
            generate(command, expand, len1,len2,convertData)
        }
    }

    private fun generate(command: Int, expand: Int, len1: Int,len2:Int, data: List<Byte> = mutableListOf()): ByteArray {
        val temp = mutableListOf(1, 16, 1, 32, command.toByte(), expand.toByte(), len1.toByte(), len2.toByte())
        data.forEach {
            temp.add(it)
        }
        val crcStr = String.format("%04X", CRC16.calcCrc16(temp.toByteArray()))
        val crcLength = crcStr.length
        val crcData = ByteArray(crcLength)
        for (i in 0 until crcLength) {
            crcData[i] = Integer.valueOf("0" + crcStr[i], 16).toByte()
        }
        val realCommand = temp.toMutableList()
        realCommand.add(crcData[2])
        realCommand.add(crcData[3])
        realCommand.add(crcData[0])
        realCommand.add(crcData[1])
        realCommand.add(0, START.toByte())
        realCommand.add(END.toByte())
        return realCommand.toByteArray()
    }
}